﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using MvcReservas.Models;
using System.ServiceModel.Web;

namespace MvcReservas.Controllers
{
    public class ClienteController : Controller
    {


        public ActionResult Index()
        {
            
            return View();
        }

        //
        // GET: /Canchita/Details/5
        //muestra pagina con datos de una canchita
        public ActionResult Details(int id)
        {
            
            return View();
        }

        //
        // GET: /Canchita/Create
        // muestra pagina para ingresar datos de creacion
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Canchita/Create
        //Recibe los datos del formulario y reliza creacion
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                //Verifica campos obligatorios
                if (collection["dni"].Equals("") || collection["nombre"].Equals("") || collection["telefono"].Equals("") || collection["correo"].Equals("") || collection["cumpleaños"].Equals(""))
                {
                    ModelState.AddModelError(String.Empty, "Usted no ha ingresado todos los datos.");
                    return View();
                }

                //Verifica DNI Unico
                HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:26288/Clientes.svc/Clientes/" + collection["dni"]);
                req2.Method = "GET";
                HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
                StreamReader reader2 = new StreamReader(res2.GetResponseStream());
                string alumnoJson2 = reader2.ReadToEnd();
                JavaScriptSerializer js2 = new JavaScriptSerializer();
                Cliente clienteObtenido = js2.Deserialize<Cliente>(alumnoJson2);
                //if(clienteObtenido!=null){
                //    ModelState.AddModelError(String.Empty, "Usuario ya esta registrado");
                //    return View();
                //}


                Cliente cliente = new Cliente()
                {

                    dni = collection["dni"],
                    nombre = collection["nombre"],
                    telefono = collection["telefono"],
                    correo = collection["correo"],
                    cumpleaños = collection["cumpleaños"]
                };
               
                JavaScriptSerializer js = new JavaScriptSerializer();
                string json=js.Serialize(cliente);



                string postdata = json;
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.
                    Create("http://localhost:26288/Clientes.svc/Clientes");
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());
                string alumnoJson = reader.ReadToEnd();
                return RedirectToAction("Edit", new { dni = cliente.dni });
            }
            catch (WebException e)
            {

                HttpWebResponse resError = (HttpWebResponse)e.Response;//
                StreamReader reader2 = new StreamReader(resError.GetResponseStream());
                string alumnoJson = reader2.ReadToEnd();
                JavaScriptSerializer js = new JavaScriptSerializer();
                Error error = js.Deserialize<Error>(alumnoJson);
                ModelState.AddModelError(String.Empty, "Error: " + error.mensajeNegocio);
                return View("Create");

            }
        }

        //
        // GET: /Canchita/Edit/5
        //muestra pagina con datos a editar
        public ActionResult Edit(string dni)
        {
            HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create("http://localhost:26288/Clientes.svc/Clientes/"+dni);
            req2.Method = "GET";
            HttpWebResponse res2 = (HttpWebResponse)req2.GetResponse();
            StreamReader reader2 = new StreamReader(res2.GetResponseStream());
            string alumnoJson2 = reader2.ReadToEnd();
            JavaScriptSerializer js2 = new JavaScriptSerializer();
            Cliente clienteObtenido = js2.Deserialize<Cliente>(alumnoJson2);

            return View(clienteObtenido);
        }


        
        public ActionResult Obtener(FormCollection collection)
        {
            try
            {

                var dniForm = collection["dni"];
                return RedirectToAction("Edit", new { dni = dniForm });
            }catch(Exception e){
                ModelState.AddModelError(String.Empty, "Error: " + e.Message);
                return View();
            }
        }
        //
        // POST: /Canchita/Edit/5
        //Recibe datos de formulario y reliza edicion
        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            try
            {

                Cliente cliente = new Cliente()
                {
                    dni = collection["dni"],
                    nombre = collection["nombre"],
                    telefono = collection["telefono"],
                    correo = collection["correo"],
                    cumpleaños = collection["cumpleaños"]
                };

                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(cliente);

                string postdata = json;
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.
                    Create("http://localhost:26288/Clientes.svc/Clientes");
                req.Method = "PUT";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                StreamReader reader = new StreamReader(res.GetResponseStream());

                return RedirectToAction("Edit", new { dni = cliente.dni });
            }
            catch (Exception e)
            {
                ModelState.AddModelError(String.Empty, "Error: " + e.Message);
                return View();
            }
        }

    }
}
